package com.example.demo.config;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Service.AddressService;
import com.example.demo.Service.CartItemService;
import com.example.demo.Service.OrderItemService;
import com.example.demo.Service.OrderService;
import com.example.demo.Util.ThreadLocallUtil;
import com.example.demo.VO.AddressInfoVo;
import com.example.demo.VO.CartItem;
import com.example.demo.VO.OrderInfoVo;
import com.example.demo.po.Address;
import com.example.demo.po.Order;
import com.example.demo.po.OrderItem;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class AiTools {
    private final OrderService ordersService;
    private final AddressService addressService;
    private final CartItemService  cartItemService;
    private final OrderItemService orderItemService;
    @Tool("智能订单查询接口，当用户需要查询时调用,返回的是")
        public List<OrderInfoVo> getOrder(@P("查询订单内容") String question){
        List<Order> userId = ordersService.list(new QueryWrapper<Order>().eq("user_id", ThreadLocallUtil.getUser().getUserId()));
        List<OrderInfoVo> orderId1 = userId.stream().map(order -> {
            OrderInfoVo orderInfoVo = new OrderInfoVo();
            // 复制相同属性
            BeanUtil.copyProperties(order, orderInfoVo);
            Address address = addressService.getById(order.getAddressId());
            if (address != null) {
                AddressInfoVo addressInfoVo = new AddressInfoVo();
                BeanUtil.copyProperties(address, addressInfoVo);
                orderInfoVo.setAddress(addressInfoVo);
            }
            List<OrderItem> orderId = orderItemService.list(new QueryWrapper<OrderItem>().eq("order_id", order.getId()));
            ArrayList<Long> objects = new ArrayList<>();
            for (OrderItem orderItem : orderId) {
                objects.add(orderItem.getCartItemId());
            }
            List<CartItem> list = objects.stream().map(cartItemId -> {
                com.example.demo.po.CartItem byId = cartItemService.getById(cartItemId);
                CartItem bean = BeanUtil.toBean(byId, CartItem.class);
                return bean;
            }).toList();
            orderInfoVo.setCartItems(list);
            return orderInfoVo;
        }).toList();
        return orderId1;
    }
}
